package com.maddox.relax.camera.c1

import android.content.Context
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.ImageFormat
import android.graphics.Matrix
import android.hardware.Camera
import android.media.AudioManager
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.view.Surface
import android.view.SurfaceHolder
import android.view.View
import android.widget.FrameLayout
import android.widget.Toast
import androidx.core.content.FileProvider
import androidx.databinding.DataBindingUtil
import com.maddox.relax.R
import com.maddox.relax.camera.MediaHelper
import com.maddox.relax.databinding.ActivityCameraPicBinding
import com.maddox.relax.util.LogUtil
import java.io.File
import java.io.FileOutputStream
import java.lang.Exception

/**
 * camera 拍照 (基于版本camera)
 *  调用方法
 *  Intent intent = new Intent(this, Camera1PicActivity.class);
 *  intent.putExtra("filePath",filePath);
 *  startActivity(intent);
 *
 */
@SuppressWarnings("all")
class Camera1PicActivity : AppCompatActivity() {

    lateinit var bd: ActivityCameraPicBinding

    private var mCamera: Camera? = null
    private var isBackCamera = true//默认后摄像
    private var mPreview: CameraPreview? = null

    //后置摄像头
    private var mBackCameraId: Int = -1
    private lateinit var mBackCameraInfo: Camera.CameraInfo

    //前置摄像头
    private var mFrontCameraId: Int = -1
    private lateinit var mFrontCameraInfo: Camera.CameraInfo

    //保存图片的地址
    private lateinit var saveImageUri: String
    //当前相机的旋转角度
    private var currentDegress = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bd = DataBindingUtil.setContentView(this, R.layout.activity_camera_pic)
        initView()
    }

    private fun initView() {
//        saveImageUri = intent.getParcelableExtra(MediaStore.EXTRA_OUTPUT) as Uri
        saveImageUri = intent.getStringExtra("filePath")

        checkCamera()
        initCameraInfo()
        safeOpenCamera()
        addPreView()
        //设置常用的监听事件
        bd.ivBack.setOnClickListener { finish() }
        //切换摄像头
        bd.exCamera.setOnClickListener {
            when (isBackCamera) {
                true -> {
                    isBackCamera = false
                    exchangeCamera()
                }
                false -> {
                    isBackCamera = true
                    exchangeCamera()
                }
            }
        }
        //进行拍照
        bd.btnPhoto.setOnClickListener {
            mCamera?.takePicture({
                try {//调用拍照声音
//                    val audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
//                    val volume = audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION)
//                    if (volume != 0) {
                        //拍照声音
//                        MediaHelper.playOneVoice(this, volume)
//                    }
                } catch (e: Exception) {
                }

            }, null, { data, camera ->
                try {//将数据进行保存
                    var bitmap = BitmapFactory.decodeByteArray(data, 0, data.size)
                    val matrix = Matrix()
                    if (!isBackCamera){
                        matrix.postRotate(currentDegress.toFloat())
                        matrix.postScale(1f,-1f,(bitmap.width/2).toFloat(),(bitmap.height/2).toFloat())
                    }else{
                        matrix.postRotate(currentDegress.toFloat())
                    }
                    var createBitmap =
                        Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
                    LogUtil.d("保存路径:${saveImageUri}")
                    val fos = FileOutputStream(saveImageUri)
                    createBitmap.compress(Bitmap.CompressFormat.JPEG,100,fos)
                    fos.flush()
                    fos.close()

                } catch (e: Exception) {
                    LogUtil.d("保存异常:${e.message}")
                }
            })
        }


    }


    //切换相机
    private fun exchangeCamera() {
        if (isBackCamera) {
            mCamera = Camera.open(mBackCameraId)
            setCameraDisplayOrientation(mBackCameraId)
        } else {
            mCamera = Camera.open(mFrontCameraId)
            setCameraDisplayOrientation(mFrontCameraId)
        }
        addPreView()
    }

    //添加预览布局
    private fun addPreView() {
        bd.cameraPreview.removeAllViews()
        //创建预览视图
        mPreview = mCamera?.let {
            CameraPreview(this, it)
        }
        //添加预览视图
        mPreview?.also {
            bd.cameraPreview.addView(it)
        }
    }

    //检查当前是否支持相机
    private fun checkCamera() {
        if (!packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            Toast.makeText(this, "当前设备不支持相机", Toast.LENGTH_SHORT).show()
            finish()
        }
    }

    //获取相机实例
    private fun safeOpenCamera() {
        if (mBackCameraId != -1) {
            mCamera = Camera.open(mBackCameraId)
            setCameraDisplayOrientation(mBackCameraId)
        } else {
            mCamera = Camera.open(mFrontCameraId)
            setCameraDisplayOrientation(mFrontCameraId)
        }


    }

    //获取本机摄像头信息
    private fun initCameraInfo() {
        //获取摄像头数量
        var numberOfCameras = Camera.getNumberOfCameras()
        //遍历摄像头
        for (cameraId in 0 until numberOfCameras) {
            //获取摄像头的信息
            val cameraInfo = Camera.CameraInfo()
            Camera.getCameraInfo(cameraId, cameraInfo)
            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                //前置摄像头
                mFrontCameraId = cameraId
                mFrontCameraInfo = cameraInfo
            } else if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
                //后置摄像头
                mBackCameraId = cameraId
                mBackCameraInfo = cameraInfo
            }
        }
        //开启相机切换
        if (mBackCameraId != -1 && mFrontCameraId != -1) {
            bd.exCamera.visibility = View.VISIBLE
        }
    }


    //设置相机预览的正确方向
    private fun setCameraDisplayOrientation(cameraId: Int) {
        val info = Camera.CameraInfo()
        Camera.getCameraInfo(cameraId, info)
        val rotation = windowManager.defaultDisplay.rotation
        var degress = 0
        when (rotation) {
            Surface.ROTATION_0 -> degress = 0
            Surface.ROTATION_90 -> degress = 90
            Surface.ROTATION_180 -> degress = 180
            Surface.ROTATION_270 -> degress = 270
        }
        var result: Int
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degress) % 360
            result = (360 - result) % 360
        } else {
            result = (info.orientation - degress + 360) % 360
        }
        currentDegress = result
        mCamera?.setDisplayOrientation(result)

    }

    override fun onDestroy() {
        super.onDestroy()
        mPreview?.apply {
            releaseCamera()
        }
    }


}